define(function (require, exports, module) {
	// 由于datepicker是在require config里面做的别名,因此require别的js需要从根目录开始算
	var utils = require("./nuui/nuui-utils/nuui-utils");
	
	var Picker = require("./nuui/nuui-component/nuui-picker");
	
	/**
	 * @class Datepicker
	 * @memberof Nuui
	 * @classdesc 利用input和picker组件创建的日历组件<br/>
	 * @param {$} input - input的$形式
	 * @param {object} config - 配置
	 * @param {string} config.title - 显示的标题<br/>
	 * @param {string} config.today - 时间基线,不传则为客户端时间<br/>
	 * @param {int} config.beginYearOffset - 最早的年份,如100年前则为-100,以时间基线为准<br/>
	 * @param {int} config.endYearOffset - 最晚的年份,以时间基线为准<br/>
	 * @param {string} config.outFormat - 格式化到输入框的日期形式,如"yyyy-mm-dd"<br/>
	 * @param {object} config.invalid - 不能选择的日期,包括daysOfWeek{array}和days{array}<br/>
	 * @param {array:int} config.invalid.daysOfWeek - 不能选择的星期,数字0对应星期天,数字6对应星期六<br/>
	 * @param {array:string} config.invalid.days - 不能选择的日期,"yyyymmdd"格式<br/>
	 * @param {view} view - 当前的view,一定要填
	 * @example var datepicker = new Datepicker(view.$("#datepicker"), { // 主要示例invalid和today,其他参数有默认设置
	 *  today:"20150824",
	 *  beginYearOffset:-100,
	 *  endYearOffset:+5,
	 *  format:"yyyymmdd",
	 *  outFormat:"yyyy-mm-dd",
	 *  invalid:{daysOfWeek:[0, 6], days:['20150506', '20150507']}
	 * }, view);
	 *
	 */
	var Datepicker = module.exports = function(input, config, view){
		this.initailize(input, config, view);
		return this;
	};
	
	Datepicker.prototype = {
		/**
		 * 初始化方法
		 */
		initailize:function(input, config, view){
			this._config = $.extend({}, this._defaultConfig);
			if(config){
				this._config = $.extend(this._config, config);
			}

			// 由于目前采取单页模式,创建时必须输入view参数
			if(!view){
				alert("datepicker:请输入view参数");
				return;
			}
			
			this._input = input;
			this._id = input.attr("id");
			this._input.data("datepicker", this);

			// 如果没有设置今天,则默认取客户端时间
			if(!this._config.today){
				this._today = new Date();
			}else{
				this._today = utils.parseDate(this._config.today, this._config.format);
			}
			
			var thisYear = this._today.getFullYear();
			
			this._beginYear = thisYear + this._config.beginYearOffset;
			
			this._endYear = thisYear + this._config.endYearOffset;
			
			this._input.bind(this._tap_event, $.proxy(this._onInputTap, this));
			// 在Safari下点击会有光标
			this._input.bind("focus", function(){this.blur();});
			
			var years = [];
			for(var i = this._beginYear; i <= this._endYear; i++){
				years.push({key:i, text:i});
			}
			
			var months = [];
			for(var i = 1; i <= 12; i++){
				months.push({key:i, text:i});
			}
			
			var days = [];
			for(var i = 1; i <= 31; i++){
				days.push({key:i, text:i});
			}

			var hours = [];
			for(var i = 0; i < 24; i++){
				hours.push({key:i, text:i});
			}

			var minutes = [];
			for(var i = 0; i < 60; i++){
				minutes.push({key:i, text:i});
			}
			
			var dp = this,
				tittle = '今天',
				content = [
					{title:"年", data:years, flex:1},
					{title:"月", data:months, flex:1},
					{title:"日", data:days, flex:1}
				];

			if(this._config.format === "yyyymmddhhmi"){
				tittle = '当前时间';
				content = content.concat([
					{title:"时", data:hours, flex:1},
					{title:"分", data:minutes, flex:1}
				]);
			}

			this._picker = new Picker({
				buttons:[{
					content:"<button class='FR'>" + tittle + "</button>",
					func:function(){
						dp._toToday(true);
					}
				}],
				scrollers:content,
				onShow:$.proxy(this._onShow, this),
				onHide:$.proxy(this._onHide, this),
				onItemSelect:$.proxy(this._onItemSelect, this)
				
			}, view);
		},
		
		/**
		 * 默认设置
		 */
		_defaultConfig:{
			title:"请选择日期",
			today:null,
			beginYearOffset:-100,
			endYearOffset:+5,
			format:"yyyymmddhhmi",
			outFormat:"yyyy-mm-dd[hh:mi]",
			invalid:{
				//daysOfWeek:[0, 6],
				days:['20150506', '20150507']}
//			invalid:null
		},
		/**
		 * 点击事件
		 */
		_tap_event:"tap",
		
		/**
		 * input对象
		 */
		_input:null,
		
		/**
		 * 时间基线,Date形式
		 */
		_today:null,
		
		/**
		 * 开始年份,int形式
		 */
		_beginYear:null,
		
		/**
		 * 结束年份,int形式
		 */
		_endYear:null,
		
		/**
		 * id
		 */
		_id:null,
		
		_config:null,

		_onInputTap:function(){
			if(this._input.attr("disabled")){
				return false;
			}
			this._picker.show();
			return false;
		},
		
		_onShow:function(){
			var value = this._input.val();
			console.log('value', value);
			if(value){
				this._scrollToDate(utils.parseDate(value, this._config.outFormat), false);
			}else{
				this._toToday(false);
			}
		},
		
		_onHide:function(result){
			if(result){
				var year = result[0];
				var month = result[1].leftPadZero(2);
				var day = result[2].leftPadZero(2);
				var dateValue = year + month + day;

				if(this._config.format === "yyyymmddhhmi"){
					var hour = result[3].leftPadZero(2);
					var minute = result[4].leftPadZero(2);
					dateValue = year + month + day + hour + minute
				}

				this._input.val(
					utils.formatDate(dateValue, this._config.format, this._config.outFormat)
				);

			}
		},
		
		_onItemSelect:function(ul, ulIndex){
			// 如果滚动的不是日期条,重新渲染日期条合法性
			if(ulIndex < 2){
				this._renderValid();
			}
			var dayUl = this._picker.getUl(2);
			var selected = dayUl.find("li.nu-picker-select");
			// 当前选中的元素不合法,选择就近元素
			// 先看前面,前面没有选后面
			// 全部都没有,再说吧
			if(!selected.hasClass("nu-picker-valid")){
				var target = selected.prevAll(".nu-picker-valid").first()[0] || selected.nextAll(".nu-picker-valid").first()[0];
				var index = dayUl.children().index(target);
				this._picker.scrollToIndex(2, index, false);
			}
		},
		
		_scrollToDate:function(date, animate){
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			var day = date.getDate();
			var value = [year, month, day];
			if(this._config.format === "yyyymmddhhmi"){
				var hour = date.getHours();
				var minute = date.getMinutes();
				value = value.concat([hour, minute]);
			}
			console.log('_scrollToDate', value);
			this._picker.scrollToValues(value, animate);
		},
		
		_toToday:function(animate){
			this._scrollToDate(this._today, animate);
		},
		
		_renderValid:function(){
			var year = this._picker.getOutput(0);
			var month = this._picker.getOutput(1).leftPadZero(2);
			
			var children = this._picker.getUl(2).children();
			children.removeClass("nu-picker-valid");
			for(var i = 1; i <= 31; i++){
				var dateStr = year + month + (i + "").leftPadZero(2);
				if(this._isValid(dateStr)){
					children.eq(i - 1).addClass("nu-picker-valid");
				}
			}
		},
		
		_isValid:function(dateStr){
			// 是否是合法日期,如2月29号之类的
			if(!utils.isDate(dateStr, "yyyymmdd")){
				return false;
			}

			// 是否是非法日期
			if(this._config.invalid && this._config.invalid.days){
				for(i in this._config.invalid.days){
					if(this._config.invalid.days[i] == dateStr){
						return false;
					}
				}
			}
			
			// 是否是非法的星期
			if(this._config.invalid && this._config.invalid.daysOfWeek){
				var weekDay = utils.parseDate(dateStr, "yyyymmdd").getDay();
				for(i in this._config.invalid.daysOfWeek){
					if(this._config.invalid.daysOfWeek[i] == weekDay){
						return false;
					}
				}
			}
			return true;
		}
	};
});
